package tasks

import (
	"context"
	"fmt"
	"proxy_resource_test/bootstrap/models"
	"proxy_resource_test/bootstrap/server"
	"proxy_resource_test/dao"
	"proxy_resource_test/services/pool_ip"
	"proxy_resource_test/utils/logging"
	"strconv"
	"time"
)

type rangeRule struct {
	Duration int64
	Name     string
}

var rules = map[string]rangeRule{
	"5":     {Duration: 300, Name: "5分钟"},
	"10":    {Duration: 600, Name: "10分钟"},
	"20":    {Duration: 1200, Name: "20分钟"},
	"30":    {Duration: 1800, Name: "30分钟"},
	"60":    {Duration: 3600, Name: "60分钟"},
	"21600": {Duration: 21600, Name: "6小时"},
	"86400": {Duration: 86400, Name: "24小时"},
}

func StartScheduler() {
	if len(pool_ip.Manager.Tasks) == 0 {
		logging.Info("no task to start", time.Now().Format(time.DateTime))
		return
	}
	now := time.Now().Unix()
	var datas []models.TaskStatistics
	var countryMap []string

	for taskID := range pool_ip.Manager.Tasks {
		// 读取redis 获取设置的popular 信息
		pop := dao.GetRedis().HGet(fmt.Sprintf("%s:%s", pool_ip.ConfigKey, taskID), "popular").Val()
		var item models.TaskStatistics
		item.Operate = taskID
		for key, rule := range rules {
			switch pop {
			case "pop":
				countryMap = pool_ip.CountryMapArr["pop"]
			case "random":
				countryMap = []string{"random"}
			default:
				countryMap = []string{pop}
			}
			for _, country := range countryMap {
				start := fmt.Sprint(now - rule.Duration)
				count, err := dao.GetRedis().ZCount(
					fmt.Sprintf("%s:%s:%s", pool_ip.TaskIpRange, taskID, country), // 获取国家范围数据
					start, fmt.Sprint(now)).Result()
				if err != nil {
					logging.Error("ZCount err:", err)
					continue
				}
				switch key {
				case "5":
					item.FiveOnly = int(count)
				case "10":
					item.TenOnly = int(count)
				case "20":
					item.TwentyOnly = int(count)
				case "30":
					item.ThirtyOnly = int(count)
				case "60":
					item.SixtyOnly = int(count)
				case "21600":
					item.SixHourOnly = int(count)
				case "86400":
					item.DayOnly = int(count)
				default:
					fmt.Print("unknown key:", key)
				}
				item.Region = country // 现在是统计维度的国家数据
				item.CreatedAt = now
				success := dao.GetRedis().Get(fmt.Sprintf("%s:%s:%s", pool_ip.TaskSuccessCounter, taskID, country)).Val()
				failNums := dao.GetRedis().Get(fmt.Sprintf("%s:%s:%s", pool_ip.TaskErrCounter, taskID, country)).Val()

				s, _ := strconv.Atoi(success)
				f, _ := strconv.Atoi(failNums)
				item.SuccessCount = s // 成功
				item.FailedCount = f  //失败

				if country != "random" {
					countrySuccess := dao.GetRedis().Get(fmt.Sprintf("%s:%s:%s", pool_ip.TaskCountrySuccess, taskID, country)).Val()
					countryFail := dao.GetRedis().Get(fmt.Sprintf("%s:%s:%s", pool_ip.TaskCountryFail, taskID, country)).Val()
					a, _ := strconv.Atoi(countrySuccess)
					b, _ := strconv.Atoi(countryFail)
					item.CountrySuccess = a /// 成功
					item.FailedCount = b    //失败
				}
				keys := fmt.Sprintf("%s:%s:%s", pool_ip.TaskDelayCount, taskID, country)
				TaskDelayCount := dao.GetRedis().Get(keys).Val()
				c, _ := strconv.ParseFloat(TaskDelayCount, 64)
				item.DelayAvg = c
				item.Region = country
				datas = append(datas, item)
			}
		}
	}
	if len(datas) > 0 {
		_ = server.InTaskStatistics(datas)
	}
	fmt.Println("start scheduler", time.Now().Format(time.DateTime))
}

// AcquireSN 按序尝试租约分配机器编号
func AcquireSN() {
	pool_ip.InitDo()
}

// StartRenew 每15 秒续期
func StartRenew() {
	pool_ip.Manager.StartRenew(context.Background())
	//logging.Error("StartRenew", time.Now().Format(time.DateTime))
}
